package com.project.m.api.busi.handlers.hicatcard.user;


import com.project.m.api.busi.config.BusiError;
import com.project.m.api.busi.db.entity.hicatcard.distributor.TDistributor;
import com.project.m.api.busi.db.entity.hicatcard.distributor.TDistributorPerson;
import com.project.m.api.busi.db.entity.hicatcard.user.TUser;
import com.project.m.api.busi.db.service.hicatcard.distributor.DistributorPersonService;
import com.project.m.api.busi.db.service.hicatcard.distributor.DistributorService;
import com.project.m.api.busi.db.service.hicatcard.user.UserService;
import com.project.m.api.busi.handlers.DefaultBizParamChecker;
import com.project.m.api.busi.bean.hicatcard.user.UserDistributorReq;
import com.project.m.api.busi.bean.hicatcard.user.UserDistributorResp;
import com.project.m.api.busi.util.TimeUtil;
import com.project.m.api.common.biz.BizHandler;
import com.project.m.api.validates.ValidateParam;
import com.project.m.api.validates.ValidateRet;
import com.project.m.api.validates.ValidateType;
import com.project.m.api.validates.ValidateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;


@Component
public class UserDistributorBizHandler extends DefaultBizParamChecker<UserDistributorReq, UserDistributorResp>
        implements BizHandler<UserDistributorReq, UserDistributorResp> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    DistributorService distributorService;

    @Autowired
    DistributorPersonService distributorPersonService;

    @Autowired
    UserService userService;

    @Override
    public UserDistributorResp handle(UserDistributorReq bizRequest) throws Exception {
        UserDistributorResp bizResp = new UserDistributorResp();
        // 参数检查
        ValidateRet vRet = checkParam(bizRequest, bizResp);
        if (!vRet.isValid()) {
            return bizResp;
        }

        try {
            //判断用户是否存在
            List<TUser> userList = userService.findByOpenidAndEnable(bizRequest.getOpenid(), true);
            if (CollectionUtils.isEmpty(userList)) {
                bizResp.setResult_code(BusiError.ERR_CODE_USER_NONE);
                bizResp.setError_message(BusiError.ERR_MSG_USER_NONE);
                return bizResp;
            }
            TUser user = userList.get(0);

            boolean hasNewDistributor = false;
            TDistributor distributor = null;
            if (!StringUtils.isEmpty(bizRequest.getDistributorNumber())) {
                //分销商是否存在
                List<TDistributor> distributorList = distributorService.findByDistributorNumberAndEnable(bizRequest.getDistributorNumber(), true);
                if (!CollectionUtils.isEmpty(distributorList)) {
                    distributor = distributorList.get(0);
                    hasNewDistributor = true;
                }
            }

            Long originDistributorId = -1l;
            if (user.getDistributorId() != null) {
                originDistributorId = user.getDistributorId();
            }

            TDistributor originDistributor = null;
            //扫渠道码进入
            if (hasNewDistributor) {

                if (originDistributorId > 0) {
                    originDistributor = distributorService.findByDistributorId(originDistributorId);
                }

                if (originDistributor == null) {
                    //原来无渠道

                    //添加渠道，记录
                    //记录distributor id 和时间
                    user.setDistributorId(distributor.getDistributorId());
                    user.setDistributorTime(TimeUtil.getCurrTime());
                    user.setUpdateTime(TimeUtil.getCurrTime());

                    TDistributorPerson distributorPerson = new TDistributorPerson();
                    distributorPerson.setDistributorId(distributor.getDistributorId());
                    distributorPerson.setUserId(user.getUserId());
                    if (distributor.getType().equalsIgnoreCase(TDistributor.TYPE_DISTRIBUTOR)) {
                        distributorPerson.setProtectEndTime(TimeUtil.getXDayLater(TimeUtil.DATE_PATTERN_NOSEPARTOR, distributor.getProtectDay()));
                    } else {
                        distributorPerson.setProtectEndTime("");
                    }

                    distributorPerson.setLoginFlag(distributor.getDistributorId());
                    distributorPerson.setCreateTime(TimeUtil.getCurrTime());
                    distributorPerson.setUpdateTime(TimeUtil.getCurrTime());

                    distributor.setTotalTimes(distributor.getTotalTimes() + 1);
                    distributor.setUpdateTime(TimeUtil.getCurrTime());

                    userService.saveUser(user);
                    distributorService.saveDistributor(distributor);
                    distributorPersonService.saveDistributorPerson(distributorPerson);
                } else {
                    //有渠道

                    boolean isChange = true;
                    if (originDistributor.getType().equalsIgnoreCase(TDistributor.TYPE_DISTRIBUTOR)) {
                        if (user.getDistributorTime().compareToIgnoreCase(TimeUtil.getXDayLater(TimeUtil.DATE_PATTERN_NOSEPARTOR, 0 - originDistributor.getProtectDay())) > 0) {
                            isChange = false;
                        }
                    }

                    if (isChange) {
                        //添加渠道，记录
                        //记录distributor id 和时间
                        user.setDistributorId(distributor.getDistributorId());
                        user.setDistributorTime(TimeUtil.getCurrTime());
                        user.setUpdateTime(TimeUtil.getCurrTime());

                        TDistributorPerson distributorPerson = new TDistributorPerson();
                        distributorPerson.setDistributorId(distributor.getDistributorId());
                        distributorPerson.setUserId(user.getUserId());
                        if (distributor.getType().equalsIgnoreCase(TDistributor.TYPE_DISTRIBUTOR)) {
                            distributorPerson.setProtectEndTime(TimeUtil.getXDayLater(TimeUtil.DATE_PATTERN_NOSEPARTOR, distributor.getProtectDay()));
                        } else {
                            distributorPerson.setProtectEndTime("");
                        }

                        distributorPerson.setLoginFlag(distributor.getDistributorId());
                        distributorPerson.setCreateTime(TimeUtil.getCurrTime());
                        distributorPerson.setUpdateTime(TimeUtil.getCurrTime());

                        distributor.setTotalTimes(distributor.getTotalTimes() + 1);
                        distributor.setUpdateTime(TimeUtil.getCurrTime());

                        originDistributor.setTotalTimes(originDistributor.getTotalTimes() - 1);
                        originDistributor.setUpdateTime(TimeUtil.getCurrTime());


                        userService.saveUser(user);
                        distributorService.saveDistributor(distributor);
                        distributorService.saveDistributor(originDistributor);
                        distributorPersonService.saveDistributorPerson(distributorPerson);

                    } else {
                        TDistributorPerson distributorPerson = new TDistributorPerson();
                        distributorPerson.setDistributorId(originDistributorId);
                        distributorPerson.setUserId(user.getUserId());
                        distributorPerson.setProtectEndTime("");
                        distributorPerson.setLoginFlag(distributor.getDistributorId());
                        distributorPerson.setCreateTime(TimeUtil.getCurrTime());
                        distributorPerson.setUpdateTime(TimeUtil.getCurrTime());
                        distributorPersonService.saveDistributorPerson(distributorPerson);
                    }
                }
            } else {


                TDistributorPerson distributorPerson = new TDistributorPerson();
                distributorPerson.setDistributorId(originDistributorId);
                distributorPerson.setUserId(user.getUserId());
                distributorPerson.setProtectEndTime("");
                distributorPerson.setLoginFlag(-1l);
                distributorPerson.setCreateTime(TimeUtil.getCurrTime());
                distributorPerson.setUpdateTime(TimeUtil.getCurrTime());
                distributorPersonService.saveDistributorPerson(distributorPerson);
            }


            /*
            //分销商是否存在
            List<TDistributor> distributorList = distributorService.findByDistributorNumberAndEnable(bizRequest.getDistributorNumber(), true);
            if (CollectionUtils.isEmpty(distributorList)) {
                bizResp.setResult_code(BusiError.ERR_CODE_DISTRIBUTOR_NONE);
                bizResp.setError_message(BusiError.ERR_MSG_DISTRIBUTOR_NONE);
                return bizResp;
            }

            TDistributor distributor = distributorList.get(0);

            //记录distributor id 和时间
            user.setDistributorId(distributor.getDistributorId());
            user.setDistributorTime(TimeUtil.getCurrTime());
            user.setUpdateTime(TimeUtil.getCurrTime());

            TDistributorPerson distributorPerson = new TDistributorPerson();
            distributorPerson.setDistributorId(distributor.getDistributorId());
            distributorPerson.setUserId(user.getUserId());
            distributorPerson.setCreateTime(TimeUtil.getCurrTime());
            distributorPerson.setUpdateTime(TimeUtil.getCurrTime());
            logger.info("distributorPerson = " + JSON.toJSONString(distributorPerson) );

            distributor.setTotalTimes(distributor.getTotalTimes() + 1);
            distributor.setUpdateTime(TimeUtil.getCurrTime());

            userService.saveUser(user);
            distributorService.saveDistributor(distributor);
            distributorPersonService.saveDistributorPerson(distributorPerson);
            */


            //返回
            bizResp.setResult_code(BusiError.ERR_CODE_SUCCESS);
            bizResp.setError_message("");
            return bizResp;

        } catch (Exception e) {
            logger.error("UserDistrobutorBizHandler", e);
            bizResp.setResult_code(BusiError.ERR_CODE_DB_SAVE);
            bizResp.setError_message(BusiError.ERR_MSG_DB_SAVE);
            return bizResp;
        }
    }

    @Override
    public ValidateRet checkParam(UserDistributorReq req, UserDistributorResp resp) {
        ValidateRet vRet = super.checkParam(req, resp);
        if (!vRet.isValid())
            return vRet;

        List<ValidateParam> paramList = new ArrayList<ValidateParam>();
        paramList.add(new ValidateParam("openid", ValidateType.NOTBLANK, req.getOpenid()));
        paramList.add(new ValidateParam("distributor_number", ValidateType.NOTBLANK, req.getDistributorNumber()));

        vRet = ValidateUtil.validate(paramList);

        if (vRet == null) {
            vRet = new ValidateRet(true, "");
        }


        if (!vRet.isValid()) {
            resp.setResult_code(BusiError.ERR_CODE_PARAM_BAD_REQ);
            resp.setError_message(vRet.getErrMsg());
        }

        return vRet;
    }
}
